#include "Entity.h"

Entity::Entity(){
	m_node = NULL;
	m_isDead = false;
	m_HP = 0;
	m_rotation = 0;
	meta = NULL;
	m_map = NULL;
}

Entity::~Entity(){

}

Node* Entity::getNode(){
	return m_node;
}

Node* Entity::getThis(){
	return (Node*)this;
}

Node* Entity::get_Parent(){
	return this->getParent();
}

void Entity::setController(Controller* controller){
	m_controller = controller;
	m_controller->setControllerListener(this);
}

bool Entity::setTagPosition(float x, float y){
	this->setPosition(Vec2(x, y));
	return true;
}

Vec2 Entity::getTagPosition(){
	return this->getPosition();
}

void Entity::hurt(int hurtValue){
	m_HP -= hurtValue;
	if (m_HP <= 0){
		m_isDead = true;
		this->onDead();
	}
}

void Entity::getBox(float x, float y){
	float l = sqrt(pow(this->getContentSize().width, 2) + pow(this->getContentSize().height, 2))/2;
	auto size = this->getContentSize();
	auto pos = Vec2(x, y);
	a[0] = Vec2(pos.x - cos(CC_DEGREES_TO_RADIANS(45 + m_rotation))*l, pos.y + sin(CC_DEGREES_TO_RADIANS(45 + m_rotation)) * l);
	a[1] = Vec2(pos.x + sin(CC_DEGREES_TO_RADIANS(45 + m_rotation))*l, pos.y + cos(CC_DEGREES_TO_RADIANS(45 + m_rotation)) * l);
	a[2] = Vec2(pos.x + cos(CC_DEGREES_TO_RADIANS(45 + m_rotation))*l, pos.y - sin(CC_DEGREES_TO_RADIANS(45 + m_rotation)) * l);
	a[3] = Vec2(pos.x - sin(CC_DEGREES_TO_RADIANS(45 + m_rotation))*l, pos.y - cos(CC_DEGREES_TO_RADIANS(45 + m_rotation)) * l);
	a[4] = (a[0] + a[1]) / 2;
	a[5] = (a[1] + a[2]) / 2;
	a[6] = (a[2] + a[3]) / 2;
	a[7] = (a[0] + a[3]) / 2;
}

bool Entity::isDead(){
	return m_isDead;
}

float Entity::getTagRotation(){
	return m_rotation;
}

void Entity::setTagRotation(float rota){
	this->setRotation(rota);
	m_rotation = rota;
}

void Entity::bindNode(Node* node){
	if (this->m_node != NULL){
		m_node->removeFromParentAndCleanup(true);
	}

	this->m_node = node;
	this->addChild(m_node);
	Size size = m_node->getContentSize();
	this->setContentSize(size);
}

void Entity::setTiledMap(TMXTiledMap* map){
	m_map = map;
	meta = m_map->getLayer("meta");
}

void Entity::onDead(){
	m_isDead = true;
	this->removeFromParentAndCleanup(true);
}

bool Entity::isInRect(Rect rect){
	for (auto pox : a){
		if (rect.containsPoint(pox)){
			return true;
		}
	}
	return false;
}

void Entity::setTankHead(float rotation){
	((Tank*)m_node)->setHeadRotation(rotation - m_rotation);
}

float Entity::getTankHead(){
	return ((Tank*)(m_node))->getHeadRotation() + m_rotation;
}
